package com.pf.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;

/**
 * AES加解密，CBC模式需要一个偏移量
 * <p>
 * 算法：AES
 * 密钥长度：128
 * 工作模式：CBC
 * 填充方式：PKCS5Padding
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/2/13 13:34
 */
@Slf4j
public class AESUtils2 {

    public static void main(String[] args) throws Exception {
        String oriStr = "测试AES加解密";
        String aesKey = getAesKey();
        String encryptStr = encrypt(oriStr, aesKey);
        String decryptStr = decrypt(encryptStr, aesKey);
        System.out.println("原字符串：" + oriStr);
        System.out.println("加密字符串：" + encryptStr);
        System.out.println("解密字符串：" + decryptStr);
    }

    /**
     * 生成128位 aesKey
     *
     * @return
     */
    private static String getAesKey() {
        try {
            //生成KEY
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] keyBytes = secretKey.getEncoded();
            //key转换
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
            String aesKey = Base64.encodeBase64String(secretKeySpec.getEncoded());
            return aesKey;
        } catch (Exception e) {
            log.error("AesUtils getAesKey error", e);
        }
        return null;
    }

    /**
     * 获取aes key
     *
     * @param keyStr
     * @return
     */
    private static SecretKeySpec getAesKey(String keyStr) {
        if (keyStr == null || "".equals(keyStr)) {
            return null;
        }
        return new SecretKeySpec(Base64.decodeBase64(keyStr), "AES");
    }


    /**
     * 加密
     *
     * @param oriStr 原字符串
     * @param aesKey AES密钥
     * @return
     * @throws GeneralSecurityException
     */
    public static String encrypt(String oriStr, String aesKey) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = getAesKey(aesKey);
        // CBC模式需要生成一个16 bytes的initialization vector:
        SecureRandom sr = SecureRandom.getInstanceStrong();
        byte[] iv = sr.generateSeed(16);
        IvParameterSpec ivps = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivps);
        byte[] data = cipher.doFinal(oriStr.getBytes());
        // IV不需要保密，把IV和密文一起返回:
        byte[] bytes = join(iv, data);
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 解密
     *
     * @param encryptStr
     * @param aesKey
     * @return
     * @throws GeneralSecurityException
     */
    public static String decrypt(String encryptStr, String aesKey) throws GeneralSecurityException {
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        // 把input分割成IV和密文:
        byte[] iv = new byte[16];
        byte[] data = new byte[encryptBytes.length - 16];
        System.arraycopy(encryptBytes, 0, iv, 0, 16);
        System.arraycopy(encryptBytes, 16, data, 0, data.length);
        // 解密:
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = getAesKey(aesKey);
        IvParameterSpec ivps = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivps);
        byte[] bytes = cipher.doFinal(data);
        return new String(bytes);
    }

    private static byte[] join(byte[] bs1, byte[] bs2) {
        byte[] r = new byte[bs1.length + bs2.length];
        System.arraycopy(bs1, 0, r, 0, bs1.length);
        System.arraycopy(bs2, 0, r, bs1.length, bs2.length);
        return r;
    }

}
